﻿using HAF.Core.Datas;
using HAF.Core.Helpers;
using HAF.LogUtility;
using HAF.SecurityLib;
using HAF.WebUtility;
using RDS.Core;
using System;
using System.IO;
using System.Threading;

namespace RDS.Author
{
    public class TokenHelper
    {
        private TokenHelper()
        {

        }

        private static TokenHelper _tokener;
        public static TokenHelper GetInstance()
        {
            return _tokener ?? (_tokener = new TokenHelper());
        }

        #region ChinaToken
        bool _deviceOver = false;
        public bool DeviceReady { get { return _deviceOver; } }

        /// <summary>
        /// 获取本机信息
        /// </summary>
        public void GetLocalDeviceInfo()
        {
            try
            {
                Thread deviceThread = new Thread(GetDevice) { Name = "deviceThread", IsBackground = true };
                deviceThread.Start();

                //new Thread(new ThreadStart(delegate
                //{
                //    GetDevice();
                //})).Start();

            }
            catch (Exception ex)
            {
                LogHelper.WriteErrorLog("获取本机设备信息异常，失败消息为：" + ex.Message);
            }
        }

        /// <summary>
        /// 获取本机设备信息
        /// </summary>
        private void GetDevice()
        {
            RuntimeAdapter.Info = new SoftwareRuntimeBase()
            {
                Device = new LocalDeviceConfig()
            };
            RuntimeAdapter.Info.Device.CpuId = ComputerInfo.GetInstance().CPUCode;
            RuntimeAdapter.Info.Device.PcName = ComputerInfo.GetInstance().ComputerName;
            RuntimeAdapter.Info.Device.OsVer = ComputerInfo.GetInstance().OsVersion;
            RuntimeAdapter.Info.Device.OsVersion = Environment.OSVersion;
            RuntimeAdapter.Info.Device.NetVersion = Environment.Version;
            RuntimeAdapter.Info.Device.Memory = ComputerInfo.GetInstance().TotalPhysicalMemory;
            RuntimeAdapter.Info.Device.Mac = ComputerInfo.GetInstance().MacAddress;
            RuntimeAdapter.Info.Device.LocalIP = ComputerInfo.GetInstance().IpAddress;
            RuntimeAdapter.Info.Device.DiskId = ComputerInfo.GetInstance().DiskID;
            RuntimeAdapter.Info.Device.SysType = ComputerInfo.GetInstance().SystemType;
            RuntimeAdapter.Info.Device.CpuCount = Environment.ProcessorCount;
            RuntimeAdapter.Info.Device.Disks = Environment.GetLogicalDrives();

            _deviceOver = true;
        }

        string _tokenFileName = Path.Combine(System.Threading.Thread.GetDomain().BaseDirectory, "RdsEngin.bin");
        /// <summary>
        /// 获取本地令牌
        /// </summary>
        public void GetChinaToken()
        {
            //1、BIN文件不存在，启动注册流程；
            //2、身份认证失败，启动注册流程。
            TokenAssistant.GetInstance().TokenedAct = TokenKitAct;
            //定义设备信息
            RuntimeAdapter.Terminal = new Terminal()
            {
                //TerCode = Guid.NewGuid().ToString("N"),
                //UID = ChinaAuthor.UserName,
                ProductCode = RuntimeAdapter.Info.ProductCode,
                FingerPrint = string.Format("{0}#{1}#{2}#{3}#{4}#{5}", RuntimeAdapter.Info.Device.OsVersion.VersionString, RuntimeAdapter.Info.Device.CpuId,
                              RuntimeAdapter.Info.Device.CpuCount, RuntimeAdapter.Info.Device.DiskId, RuntimeAdapter.Info.Device.Mac, RuntimeAdapter.Info.Device.Memory),
                ReqIP = IP4Helper.IpToLong(RuntimeAdapter.Info.Device.LocalIP),
                //Token = ChinaAuthor.UserToken,
                VER = RuntimeAdapter.Info.ProductVersion,
                DEV = RuntimeAdapter.Info.DevVersion
                //TimeStamp = LogHelper.GetTimeStamp(true)
            };
            if (File.Exists(_tokenFileName))
            {
                TokenAssistant.GetInstance().TokenVerify(RuntimeAdapter.Terminal, _tokenFileName);
            }
            else
            {
                LogHelper.WriteErrorLog("CHINATOKEN：用户身份匹配信息不存在，根据风控策略将当前软件判定为新拷贝，启动注册流程");
                TokenAssistant.GetInstance().GetToken(RuntimeAdapter.Terminal, _tokenFileName);
            }
        }

        /// <summary>
        /// 委托方法
        /// </summary>
        /// <param name="token"></param>
        private void TokenKitAct(ChinaToken token)
        {
            if (token.Code == -1)
            {
                LogHelper.WriteErrorLog("CHINATOKEN：用户身份认证失败，根据风控策略将当前软件判定为新拷贝并启动注册流程");
                TokenAssistant.GetInstance().TokenClear(_tokenFileName);
                TokenAssistant.GetInstance().GetToken(RuntimeAdapter.Terminal, _tokenFileName);
                return;
            }
            else
            {
                //ChinaAuthor.UserToken = token.Token;
                //ChinaAuthor.AppTag = token.DeviceCode;
                //ChinaAuthor.UserName = "KillJD" + token.Key.ToString();
                RuntimeAdapter.Terminal.TerCode = token.DeviceCode;
                RuntimeAdapter.Terminal.Token = token.Token;
                RuntimeAdapter.Terminal.UID = "KillJD" + token.Key.ToString();
                //ChinaAuthor.ProductVerify = true;
                //认证成功后进行网络注册操作
                if (token.Code == 1) Author.GetInstance().Regist();

                LogHelper.WriteInfoLog("用户身份匹配成功，当前用户令牌为" + token.Token);

            }
        }

        #endregion ChinaToken
    }
}
